<template>
  <!-- 这里itemWidth-itemSpace多减一是为了少偏移一点，防止出现缝隙 -->
  <div class="slides" :style="`--hover-translate:${-(itemWidth-itemSpace-1)}vmax`">
    <div
      :class="['slide', {'slide-hover': index > 0}]"
      v-for="(item, index) in computedList"
      :key="itemKey ? item[itemKey] : item"
      :style="{
        width: item.width,
        left: item.left,
      }"
      @mouseover="handleHover(index)"
      @click="handleHover(index)"
    >
    <slot :item="item" :index="index" :hoverIndex="hoverIndex"></slot>
  </div>
  </div>
</template>

<script lang="ts" setup name="slides">
import { ref, computed } from "vue";
const hoverIndex = ref(0);
const props = withDefaults(defineProps<{
  itemWidth?: number; // 每个元素宽度，按百分比算，0-100
  list?: any[];
  itemKey?: string;
}>(), {
  itemWidth: 60,
  list: () => [],
})

// 视口剩余空间中每个元素分到的宽度
const itemSpace = (100 - props.itemWidth) / (props.list.length - 1);
const computedList = computed(() => {
  return props.list.map((item, index) => {
    return {
      data: item,
      width: props.itemWidth + '%',
      left: index > 1 ? -((index - 1) * props.itemWidth - (index - 1) * itemSpace) + 'vmax' : 0,
    }
  })
})

const emit = defineEmits(['hover'])
const handleHover = (index: number) => {
  hoverIndex.value = index;
  emit('hover', index)
}
</script>

<style lang="scss" scoped>
.slides {
  display: block;
  width: 100%;
  height: 100%;
  overflow: hidden;
  white-space: nowrap;
  .slide {
    display: inline-block;
    height: 100%;
    position: relative;
    transition: transform 0.6s;
  }
  .slide-hover:hover, .slide-hover:has(~.slide-hover:hover) {
    // 鼠标悬停在当前元素上，以及当前元素前面的
    transform: translateX(var(--hover-translate));
  }
}
</style>
